<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Django模板系统 | 如是的学习博客</title><meta name="keywords" content="django"><meta name="author" content="rushiy"><meta name="copyright" content="rushiy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="官方文档：https:&#x2F;&#x2F;docs.djangoproject.com&#x2F;zh-hans&#x2F;3.0&#x2F;ref&#x2F;templates&#x2F;builtins&#x2F;#std:templatetag-for 关于模板渲染，只需要记两种特殊符号（即语法）：  &amp;#123;&amp;#123; var &amp;#125;&amp;#125;：调用变量var &amp;#123;% %&amp;#125;：与逻辑相关，常与if、for逻辑语句一起使用。  模板是什">
<meta property="og:type" content="article">
<meta property="og:title" content="Django模板系统">
<meta property="og:url" content="https://rushiy.gitee.io/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/index.html">
<meta property="og:site_name" content="如是的学习博客">
<meta property="og:description" content="官方文档：https:&#x2F;&#x2F;docs.djangoproject.com&#x2F;zh-hans&#x2F;3.0&#x2F;ref&#x2F;templates&#x2F;builtins&#x2F;#std:templatetag-for 关于模板渲染，只需要记两种特殊符号（即语法）：  &amp;#123;&amp;#123; var &amp;#125;&amp;#125;：调用变量var &amp;#123;% %&amp;#125;：与逻辑相关，常与if、for逻辑语句一起使用。  模板是什">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-04T07:08:03.000Z">
<meta property="article:author" content="rushiy">
<meta property="article:tag" content="django">
<meta name="twitter:card" content="summary"><link rel="shortcut icon" href="/img/favicon.jpg"><link rel="canonical" href="https://rushiy.gitee.io/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Django模板系统',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-11-19 01:18:40'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/favicon.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">如是的学习博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Django模板系统</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-04T07:08:03.000Z" title="发表于 2022-11-04 15:08:03">2022-11-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-18T17:18:40.362Z" title="更新于 2022-11-19 01:18:40">2022-11-19</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Django模板系统"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>官方文档：<code>https://docs.djangoproject.com/zh-hans/3.0/ref/templates/builtins/#std:templatetag-for</code></p>
<p>关于模板渲染，只需要记两种特殊符号（即语法）：</p>
<ul>
<li><code>&#123;&#123; var &#125;&#125;</code>：调用变量<code>var</code></li>
<li><code>&#123;% %&#125;</code>：与逻辑相关，常与<code>if</code>、<code>for</code>逻辑语句一起使用。</li>
</ul>
<h2 id="模板是什么"><a href="#模板是什么" class="headerlink" title="模板是什么"></a>模板是什么</h2><h3 id="Web模板系统"><a href="#Web模板系统" class="headerlink" title="Web模板系统"></a><code>Web</code>模板系统</h3><p>一个模板的渲染需要三方参与: </p>
<ul>
<li><code>模板引擎</code>：主要参与模板渲染的系统；</li>
<li><code>内容源</code>：输入的数据，比较常见的有<code>数据库</code>、<code>XML文件</code>等</li>
<li><code>模板</code>：一般是和语言相关的文本</li>
</ul>
<p>模板系统的工作过程如图所示。</p>
<p><img src="/pic/django-pic/image-20221110115634756.png" alt="image-20221110115634756"></p>
<p>由图可知, 模板和内容源由模板引擎处理和组合, 批量生成Web文档。</p>
<h3 id="DTL模板"><a href="#DTL模板" class="headerlink" title="DTL模板"></a><code>DTL</code>模板</h3><p>我们知道，视图函数只是直接返回文本，而在实际生产环境中其实很少这样用，因为实际的页面大多是带有样式的<code>HTML</code>代码， 这可以让浏览器渲染出非常漂亮的页面。</p>
<p>目前市面上有非常多的模板系统，其中最知名最好用的就是<code>DTL</code>和<code>jinja2</code>。<code>DTL</code>是<code>Django Template Language</code>三个单词的缩写，也就是<code>Django</code>自带的模板语言。当然也可以配置<code>Django</code>支持<code>jinja2</code>等其他模板引擎, 但是作为<code>Django</code>内置的模板语言, 和<code>Django</code>可以达到无缝衔接而不会产生一些不兼容的情况。</p>
<p><code>DTL</code>与普通的<code>HTML</code>的区别：<code>DTL</code>模板是一种带有特殊语法的<code>HTML</code>文件，这个<code>HTML</code>文件可以被<code>Django</code>编译，可以传递参数进去， 实现数据动态化。在编译完成后，生成一个普通的HTML文件，然后发送给客户端。</p>
<h4 id="渲染模板"><a href="#渲染模板" class="headerlink" title="渲染模板"></a>渲染模板</h4><p>渲染模板有多种方式，常见的是如下的两种方式：</p>
<ol>
<li><code>render_to_string</code>: 找到模板，然后将模板编译后渲染成Python的字符串格式。最后再通过<code>HttpResponse</code>类包装成一个<code>HttpResponse</code>对象返回回去。示例代码如下:</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.template.loader <span class="keyword">import</span> render_to_string</span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">book_detail</span>(<span class="params">request, book_id</span>):</span><br><span class="line">    html = render_to_string(<span class="string">&#x27;detail.html&#x27;</span>)</span><br><span class="line">    <span class="keyword">return</span> HttpResponse(html)</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>Django还提供了一个更加简便的方式，直接将模板渲染成字符串后包装成<code>HttpResponse</code>对象一步到位完成。示例代码如下:</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">book_list</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&#x27;list.html&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="模板查找路径"><a href="#模板查找路径" class="headerlink" title="模板查找路径"></a>模板查找路径</h3><p>在项目的<code>settings.py</code>文件中，有一个<code>TEMPLATES</code>配置，这个配置包含了模板引擎的配置、模板查找路径的配置、模板上下文配置等。</p>
<p><img src="/pic/django-pic/image-20221110120752598.png" alt="image-20221110120752598"></p>
<p>模板路径可以在两个地方配置：</p>
<ul>
<li><p><code>DIRS</code>: 这是一个列表，在这个列表中可以存放所有的模板路径，以后在视图中使用<code>render</code>或者<code>render_to_string</code>渲染模板的时候， 会在这个列表的路居中查找模板 。</p>
</li>
<li><p><code>APP_DIRS</code>: <code>默认为True</code>，这个设置为<code>True</code>后，会在<code>INSTALLED_APPS</code>的安装了的<code>APP</code>下的<code>templates</code>文件夹中查找模板。</p>
</li>
</ul>
<p>查找顺序: 比如代码<code>render(&#39;list.html&#39;)</code>。先会在<code>DIRS</code>这个列表中依次查找路径下有没有这个模板，如果有，就返回。如果<code>DIR</code>列表中所有的路径都没有找到，那么会先检查当前这个视图所处的<code>app</code>是否已经安装，如果已经安装了，那么就先在当前这个<code>app</code>下的<code>templates</code>文件夹中查找模板，如果没有找到，那么会在其他已经安装了的<code>app</code>中查找。如果所有路径下都没有找到，那么会抛出一个<code>TemplatesDoesNotExist</code> 的异常。</p>
<hr>
<h2 id="模板变量"><a href="#模板变量" class="headerlink" title="模板变量"></a>模板变量</h2><p>在<code>Django</code>的模板语言中按此语法调用变量：<code>&#123;&#123; 变量名 &#125;&#125;</code>。</p>
<p>模板中可以包含变量，当模版引擎遇到一个变量，它将计算这个变量，然后用结果替换掉它本身。 变量的命名包括任何字母数字以及下划线 <code>_</code>的组合。 变量名称中不能有<code>空格</code>、<code>点号</code>等特殊标点符号。</p>
<blockquote>
<p><code>.</code>号是深度查询的符号。</p>
</blockquote>
<p><code>.</code>(点号)在模板语言中有特殊的含义。当模版系统遇到<code>.</code>符号，它将以这样的顺序查询，比如<code>person.username</code>：</p>
<ul>
<li>字典查询（<code>Dictionary lookup</code>）：如果<code>person</code>是一个字典，那么就会查找这个字典的<code>username</code>这个<code>key</code>对应的值；</li>
<li>属性或方法查询（<code>Attribute or method lookup</code>）：如果<code>person</code>是一个对象，那么就会查找这个对象的<code>username</code>属性，或者是<code>username</code>这个方法；</li>
<li>数字索引查询（<code>Numeric index lookup</code>）：如果出现的是<code>person.1</code>，会判断<code>persons</code>是否是一个列表或者元组或者任意可以通过下标访问的对象，如果是的话就获取这个列表的第一个值，如果不是就获取到的是一个空的字符串。</li>
</ul>
<p>注意事项：</p>
<ul>
<li>如果计算结果的值是可调用的，它将被无参数的调用。 调用的结果将成为模版的值。</li>
<li>如果使用的变量不存在， 模版系统将插入<code>string_if_invalid</code>选项的值， 它被默认设置为’’ (空字符串) 。</li>
<li>不能通过<code>中括号</code>的形式访问字典和列表中的值，比如<code>dict[&#39;key&#39;]</code>和<code>list[1]</code>是不支持的！！！</li>
<li>因为使用<code>点(.)</code>语法获取对象的时候，可以获取这个对象的属性，如果这个对象是一个字典，也可以获取这个字典的值，因此不能在字典中定义字典本身就有的属性当做<code>key</code>，否则字典的那个属性将变成字典中的<code>key</code>了。</li>
</ul>
<p>变量需要通过视图函数渲染，视图函数是在使用<code>render</code>或者<code>render_to_string</code>的时候可以传递一个<code>context</code>的参数，这个参数是一个字典类型。以后在模板中的变量就从这个字典中读取值的。</p>
<blockquote>
<p>模板变量是在函数视图<code>render</code>或者<code>render_to_string</code>中的<code>context</code>使用，获取值的方式类似于字典。</p>
</blockquote>
<p>一个简单的视图和模板的对应关系如下：</p>
<ul>
<li>html模板</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># user.html模板代码</span><br><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; username &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span>      # 调用变量username，此处的username是视图函数传递给模板的</span><br></pre></td></tr></table></figure>

<ul>
<li>视图函数</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># views.py代码</span></span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">profile</span>(<span class="params">request</span>):</span><br><span class="line">    username = <span class="string">&quot;zhangsan&quot;</span>      <span class="comment"># 定义一个用户名</span></span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&#x27;profile.html&#x27;</span>, context=&#123;<span class="string">&#x27;username&#x27;</span>: username&#125;)</span><br><span class="line">    <span class="comment"># return render(request, &#x27;profile.html&#x27;, &#123;&#x27;username&#x27;: username&#125;)  # context=可省略</span></span><br></pre></td></tr></table></figure>

<h3 id="局部变量"><a href="#局部变量" class="headerlink" title="局部变量"></a>局部变量</h3><p>特定视图函数传递给<code>html</code>模板，仅在视图函数和对应的<code>html</code>模板中有效。</p>
<ul>
<li>路由</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 根路由</span></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path, include</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">&quot;myapp/&quot;</span>, include(<span class="string">&quot;myapp.urls&quot;</span>)),</span><br><span class="line">    path(<span class="string">&quot;myblog/&quot;</span>, include(<span class="string">&quot;blog.urls&quot;</span>))</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="comment">## 从路由</span></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> re_path</span><br><span class="line"><span class="keyword">from</span> myapp <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    re_path(<span class="string">&#x27;^user_info/$&#x27;</span>, views.user_info, name=<span class="string">&quot;user_info&quot;</span>)</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<ul>
<li>视图函数</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">user_info</span>(<span class="params">request</span>):</span><br><span class="line">    user = &#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;zhangsan&#x27;</span>, <span class="string">&#x27;property&#x27;</span>: &#123;<span class="string">&#x27;sex&#x27;</span>: <span class="string">&#x27;男&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">18</span>&#125;&#125;</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&#x27;user.html&#x27;</span>, &#123;<span class="string">&#x27;user&#x27;</span>: user&#125;)</span><br></pre></td></tr></table></figure>

<ul>
<li>html模板</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>用户信息<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        传递过来的字典: &#123;&#123; user &#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">        姓名: &#123;&#123; user.name &#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">        性别: &#123;&#123; user.property.sex &#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">        年龄: &#123;&#123; user.property.age &#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>浏览器访问</li>
</ul>
<p><img src="/pic/django-pic/image-20221109234228900.png" alt="image-20221109234228900"></p>
<h3 id="全局变量"><a href="#全局变量" class="headerlink" title="全局变量"></a>全局变量</h3><p>在网页制作中，有些变量需要定义为全局变量，如登录的用户信息。如下某电商平台，当用户登录后，无论点击哪个网页，登录用户的用户名永远都显示，这种情况就需要使用全局变量，可以在全局引用。</p>
<p><img src="/pic/django-pic/image-20221109235045422.png" alt="image-20221109235045422"></p>
<h4 id="设置全局变量"><a href="#设置全局变量" class="headerlink" title="设置全局变量"></a>设置全局变量</h4><p>在项目根目录下新建<code>contexts.py</code>文件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">user</span>(<span class="params">request</span>):</span><br><span class="line">    username = <span class="string">&quot;zhangsan&quot;</span></span><br><span class="line">    <span class="keyword">return</span> &#123;<span class="string">&quot;username&quot;</span>: username&#125;</span><br></pre></td></tr></table></figure>

<p>在项目配置文件<code>settings.py</code>中引用该变量。</p>
<p><img src="/pic/django-pic/image-20221110000204285.png" alt="image-20221110000204285"></p>
<h4 id="使用全局变量"><a href="#使用全局变量" class="headerlink" title="使用全局变量"></a>使用全局变量</h4><ul>
<li>路由</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 根路由</span></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path, include</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">&quot;myapp/&quot;</span>, include(<span class="string">&quot;myapp.urls&quot;</span>))</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="comment">## 从路由</span></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> re_path</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> re_path</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    re_path(<span class="string">&quot;^username/&quot;</span>, views.username, name=<span class="string">&quot;username&quot;</span>)</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<ul>
<li>视图函数</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">username</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&quot;username.html&quot;</span>)</span><br></pre></td></tr></table></figure>

<ul>
<li>html模板</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>用户<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h3</span>&gt;</span>欢迎：&#123;&#123; username &#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>效果：</p>
<p><img src="/pic/django-pic/image-20221110000452346.png" alt="image-20221110000452346"></p>
<hr>
<h2 id="标签tags"><a href="#标签tags" class="headerlink" title="标签tags"></a>标签tags</h2><p><code>模板</code>标签都是放在<code>&#123;% xxx %&#125;</code>括号里的，模板标签的本质也是函数，标签名一般即为函数名。这些标签的主要作用包括载入代码渲染模板或对传递过来的参数进行一定的逻辑判断或计算后返回。</p>
<p>常见的模板标签有：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>标签</th>
<th>用途</th>
<th>基本用法</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td><code>if/else</code></td>
<td>条件判断</td>
<td><code>&#123;% if condition %&#125; … &#123;% endif %&#125;</code></td>
</tr>
<tr>
<td>2</td>
<td><code>for</code></td>
<td>循环遍历</td>
<td><code>&#123;% for athlete in athlete_list %&#125; … &#123;% endfor %&#125;</code></td>
</tr>
<tr>
<td>3</td>
<td><code>ifequal/ifnotequal</code></td>
<td>值比较</td>
<td><code>&#123;% ifequal user currentuser %&#125; … &#123;% endifequal %&#125;</code></td>
</tr>
<tr>
<td>4</td>
<td><code>注释标签</code></td>
<td>注释</td>
<td>&#96;&#96;</td>
</tr>
<tr>
<td>5</td>
<td><code>include</code></td>
<td>包含其他模板</td>
<td><code>&#123;% include “nav.html” %&#125;</code></td>
</tr>
</tbody></table>
<blockquote>
<p>注意：写<code>if/else</code>、<code>for</code>标签时，一定要记得写<code>endif</code>、<code>endfor</code>。</p>
</blockquote>
<h3 id="for标签"><a href="#for标签" class="headerlink" title="for标签"></a><code>for</code>标签</h3><p><code>for循环</code>：一般用于遍历数据类型的元素进行处理，例如列表。<code>for...in...</code>类似于<code>Python</code>中的<code>for...in...</code>。可以遍历列表、元组、字符串、字典等一切可以遍历的对象。</p>
<p>格式如下：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;% for <span class="tag">&lt;<span class="name">变量</span>&gt;</span> in <span class="tag">&lt;<span class="name">序列</span>&gt;</span> %&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">内容块</span>&gt;</span> </span><br><span class="line">&#123;% endfor %&#125;</span><br></pre></td></tr></table></figure>

<p>可以利用&#96;</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://rushiy.gitee.io">rushiy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://rushiy.gitee.io/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/">https://rushiy.gitee.io/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://rushiy.gitee.io" target="_blank">如是的学习博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/django/">django</a></div><div class="post_share"><div class="social-share" data-image="" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/favicon.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">rushiy</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:rushiy@reg.email.cn" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E6%9D%BF%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.</span> <span class="toc-text">模板是什么</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Web%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F"><span class="toc-number">1.1.</span> <span class="toc-text">Web模板系统</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DTL%E6%A8%A1%E6%9D%BF"><span class="toc-number">1.2.</span> <span class="toc-text">DTL模板</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B8%B2%E6%9F%93%E6%A8%A1%E6%9D%BF"><span class="toc-number">1.2.1.</span> <span class="toc-text">渲染模板</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E6%9D%BF%E6%9F%A5%E6%89%BE%E8%B7%AF%E5%BE%84"><span class="toc-number">1.3.</span> <span class="toc-text">模板查找路径</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E6%9D%BF%E5%8F%98%E9%87%8F"><span class="toc-number">2.</span> <span class="toc-text">模板变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-number">2.1.</span> <span class="toc-text">局部变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="toc-number">2.2.</span> <span class="toc-text">全局变量</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="toc-number">2.2.1.</span> <span class="toc-text">设置全局变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="toc-number">2.2.2.</span> <span class="toc-text">使用全局变量</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A0%87%E7%AD%BEtags"><span class="toc-number">3.</span> <span class="toc-text">标签tags</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#for%E6%A0%87%E7%AD%BE"><span class="toc-number">3.1.</span> <span class="toc-text">for标签</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/" title="Django模板系统"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django模板系统"/></a><div class="content"><a class="title" href="/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/" title="Django模板系统">Django模板系统</a><time datetime="2022-11-04T07:08:03.000Z" title="发表于 2022-11-04 15:08:03">2022-11-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E8%A7%86%E5%9B%BE/" title="Django视图"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django视图"/></a><div class="content"><a class="title" href="/django/Django%E8%A7%86%E5%9B%BE/" title="Django视图">Django视图</a><time datetime="2022-11-03T07:07:51.000Z" title="发表于 2022-11-03 15:07:51">2022-11-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E8%B7%AF%E7%94%B1%E7%B3%BB%E7%BB%9F/" title="Django路由系统"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django路由系统"/></a><div class="content"><a class="title" href="/django/Django%E8%B7%AF%E7%94%B1%E7%B3%BB%E7%BB%9F/" title="Django路由系统">Django路由系统</a><time datetime="2022-11-02T07:07:34.000Z" title="发表于 2022-11-02 15:07:34">2022-11-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/%E8%B5%B0%E8%BF%9BDjango/" title="走进Django"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="走进Django"/></a><div class="content"><a class="title" href="/django/%E8%B5%B0%E8%BF%9BDjango/" title="走进Django">走进Django</a><time datetime="2022-11-01T07:01:20.000Z" title="发表于 2022-11-01 15:01:20">2022-11-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/python/python%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/" title="python常用模块"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="python常用模块"/></a><div class="content"><a class="title" href="/python/python%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/" title="python常用模块">python常用模块</a><time datetime="2022-10-28T15:34:07.000Z" title="发表于 2022-10-28 23:34:07">2022-10-28</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 By rushiy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>